package com.wu.leetcode.leetcode40;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;


/**
 * Leetcode40-组合总和 II
 *
 * @author lynn
 * @date 2020/8/17 - 19:30
 */
class Solution {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0 || target < 0) {
            return res;
        }
        Arrays.sort(candidates);
        dfs(candidates, new ArrayList<>(), target, 0);
        return res;
    }

    private void dfs(int[] candidates, ArrayList<Integer> list, int target, int index) {
        //满足结束条件
        if (target == 0) {
            res.add(new LinkedList(list));
            return;
        }
        if (target > 0) {
            //选择列表，并加上约束
            for (int i = index; i < candidates.length; i++) {
                //如果以当前结点为头结点的所有组合都找完了，那么下一个与他他相同的头结点就不用去找了。
                if (i > index && candidates[i] == candidates[i - 1]) {
                    continue;
                }
                //做出选择
                list.add(candidates[i]);
                dfs(candidates, list, target - candidates[i], i + 1);
                //撤销选择
                list.remove(list.size() - 1);
            }
        }
    }
}